package it.nm.unipicontrol.ui;

import it.nm.unipicontrol.gateway.UniPIGateway;
import it.nm.unipicontrol.gateway.event.UniPiEvent;
import it.nm.unipicontrol.gateway.event.UniPiRelayEvent;
import it.nm.unipicontrol.gateway.event.UniPiRelayEventListener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JButton;

public class RelayButton extends JButton {

	private final String IMG_OPEN = "button_turn_off_01.png"; 
	private final String IMG_CLOSE  = "button_turn_on_01.png"; 
	private final String UNKNOWN = "help_purple_button.png";
	
	private int relay = -1;
	
    private static final Logger logger = Logger.getLogger(RelayButton.class.getName());
	private static final int STATUS_UNKNOWN = -1;
	private static final int STATUS_OPEN = 0;
	private static final int STATUS_CLOSE = 1;
	
	
	private boolean connected = false;
	private int relayStatus;

	public RelayButton() {
		super();
		setLayout();
	}

	public RelayButton(String text) {
		super(text);
		setLayout();

	}

	private void setLayout() {

		try {
			
			connected = false;
			relayStatus = STATUS_UNKNOWN;
			

			setSize(32, 32);
			setContentAreaFilled(false);
			setBorderPainted(false);
			setIcon(new ImageIcon(getClass().getResource(UNKNOWN),"not known"));
			setEnabled(false);
			setRelayStatus(STATUS_UNKNOWN);
			
//	        addChangeListener(new ChangeListener() {
//				
//				@Override
//				public void stateChanged(ChangeEvent e) {
//	                if (getModel().isPressed()) {
//	                	//setIcon(new ImageIcon(getClass().getResource(ON),"on"));
//	                	//setRelayStatus(STATUS_CLOSED);
//	                } else if (getModel().isRollover()) {
//
//	                } else {
//	                	//setIcon(new ImageIcon(getClass().getResource(OFF),"off"));
//	                	//setRelayStatus(STATUS_OPEN);	                	
//	                }
//				}
//			});
	        
	        
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		//standard hard-coded event handling to unipi events
		final RelayButton my = this;

		UniPIGateway.INSTANCE.addEventListener(new UniPiRelayEventListener() {
			
			public void handleUniPiClassEvent(UniPiEvent e) {
				if ((e instanceof UniPiRelayEvent)) {
					UniPiRelayEvent r = (UniPiRelayEvent)e;
					if (r.getRelay() == my.getRelay()) {

						my.getModel().setEnabled(r.getStatus() != -1);
						//my.getModel().setPressed(r.getStatus() == 0? true: false);
						
						if (r.getStatus() == 1) {
							my.setRelayStatus(STATUS_CLOSE);
							setIcon(new ImageIcon(getClass().getResource(IMG_CLOSE),"on"));
						} else {
							my.setRelayStatus(STATUS_OPEN);
							setIcon(new ImageIcon(getClass().getResource(IMG_OPEN),"off"));
						}
						
					}
				}
			}
		});

		
	addActionListener(new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				if (!(my.getRelayStatus() == RelayButton.STATUS_UNKNOWN)) {
					
				//translate the status
				boolean oldStatus = false;
				if (my.getRelayStatus() == STATUS_CLOSE) oldStatus = true;
				if (my.getRelayStatus() == STATUS_OPEN) oldStatus = false;
					
				boolean newStatus  = (UniPIGateway.INSTANCE.setRelay(my.getRelay(),!oldStatus));
				
				logger.log(Level.FINE,"clicked relay "+ my.relay + " old value = "+ my.getRelayStatus() + " new value = "+ newStatus);
				
				my.setRelayStatus(newStatus?1:0);
				if (newStatus == true) {
					setIcon(new ImageIcon(getClass().getResource(IMG_CLOSE),"on"));
				} else {
					setIcon(new ImageIcon(getClass().getResource(IMG_OPEN),"on"));
				}

				logger.log(Level.FINE,"set relay "+ my.relay + " status: " +my.getRelayStatus());		
				
				} else {
					logger.log(Level.INFO,"clicked relay "+ my.relay + " on status UNKNOWN");
				}
			} catch (Exception e1) {
				my.setRelayStatus(STATUS_UNKNOWN);
				logger.log(Level.SEVERE,e1.getMessage(),e1);
			}
		}
	});

	}

	public void setRelayStatus(int status) {
		this.relayStatus = status;
		
	}

	public int getRelayStatus() {
		// TODO Auto-generated method stub
		return relayStatus;
	}

	public boolean isConnected() {
		return connected;
	}

	public void setConnected(boolean connected) {
		setEnabled(connected);
		if (!connected && relay != -1) {
        	setIcon(new ImageIcon(getClass().getResource(UNKNOWN),"unknown"));
        	try {
				boolean r = UniPIGateway.INSTANCE.getRelay(relay);
			} catch (Exception e) {
				logger.log(Level.FINE, "error reading relay " + relay + " status ");
			}
		}
		this.connected = connected;
	}

	public int getRelay() {
		return relay;
	}

	public void setRelay(int relay) {
		this.relay = relay;
	}
	


}
